package cat.joronya.supermanager.service.substrImpl;

import java.util.Hashtable;

import android.util.Log;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.service.DayMatchesParser;

public class DayMatchesParserImpl implements DayMatchesParser
{
	// left team
	private static final String LEFT_TEAM_START = "<td class=\"naranjaclaro\" align=\"right\">";
	private static final String LEFT_TEAM_STOP = " |";
	
	// right team
	private static final String RIGHT_TEAM_START = "<td class=\"naranjaclaro\" align=\"left\">";
	private static final String RIGHT_TEAM_STOP = "</td>";
	
	// has link?
	private static final String START_LINK = "<a ";
	private static final String START_LINK2 = "\">";
	private static final String STOP_LINK = "</a>";
	
	// matches hashtable
	private Hashtable<String, String> matches = new Hashtable<String, String>();

	public long parse(String html) throws Exception 
	{
		long start = System.nanoTime();

		try
		{
			int leftStart = html.indexOf(LEFT_TEAM_START);
			if( leftStart == -1 )
				throw new Exception();
			
			int leftStop, rightStart, rightStop;
			String leftTeam, rightTeam, homeTeam, vsTeam;
			
			// mentres tinguem noves files voltem
			while( leftStart != -1 )
			{
				// team left
				leftStop = html.indexOf(LEFT_TEAM_STOP, leftStart+LEFT_TEAM_START.length());
				leftTeam = html.substring(leftStart+LEFT_TEAM_START.length(), leftStop);
				if( leftTeam.indexOf(START_LINK) != -1 )
				{
					int leftStart2 = leftTeam.indexOf(START_LINK2);
					int leftStop2 = leftTeam.indexOf(STOP_LINK, leftStart2+START_LINK2.length());
					leftTeam = leftTeam.substring(leftStart2+START_LINK2.length(), leftStop2);
				}
				homeTeam = teamNameToAcronim.get(leftTeam);
				
				// team right
				rightStart = html.indexOf(RIGHT_TEAM_START, leftStop+LEFT_TEAM_STOP.length());
				rightStop = html.indexOf(RIGHT_TEAM_STOP, rightStart+RIGHT_TEAM_START.length());
				rightTeam = html.substring(rightStart+RIGHT_TEAM_START.length(), rightStop);
				if( rightTeam.indexOf(START_LINK) != -1 )
				{
					int rightStart2 = rightTeam.indexOf(START_LINK2);
					int rightStop2 = rightTeam.indexOf(STOP_LINK, rightStart2+START_LINK2.length());
					rightTeam = rightTeam.substring(rightStart2+START_LINK2.length(), rightStop2);
				}
				vsTeam = teamNameToAcronim.get(rightTeam);
				
				// store teams only if parsed
				if( homeTeam != null && vsTeam != null && 
						!"".equals(homeTeam) && !"".equals(vsTeam) )
				{
					Log.d(Supermanager.TAG,"DayMatchesParser.parse found match: "+homeTeam+" vs "+vsTeam);
					matches.put(homeTeam, vsTeam);
					matches.put(vsTeam, homeTeam);
				}
				
				// nova left
				leftStart = html.indexOf(LEFT_TEAM_START, rightStop+RIGHT_TEAM_STOP.length());
			}
		}
		catch(Exception e)
		{}
				
		return System.nanoTime()-start;
	}

	public Hashtable<String, String> getDayMatches() 
	{
		return matches;
	}
}

